package com.young.web;

import com.young.domain.User;
import org.springframework.web.bind.annotation.*;

import java.util.*;

/*
* Spring4之后加入的注解，原来在@Controller中返回json需要@ResponseBody来配合，
* 如果直接用@RestController替代@Controller就不需要再配置
* */
@RestController
@RequestMapping(value="/users")
public class UserController {
    //创建线程安全的map
    static Map<Long,User> users = Collections.synchronizedMap(new HashMap<Long,User>());

    @RequestMapping(value = "/",method = RequestMethod.GET)
    public List<User> getUserList() {
        //可通过@RequestParam从页面传递参数来进行查询或者翻页
        List<User> r = new ArrayList<User>(users.values());
        return r;
    }

    @RequestMapping(value="/",method = RequestMethod.POST)
    public String postUser(@ModelAttribute User user)
    {
        //@ModelAttribute会将客户端传递过来的参数按名称注入到指定对象中，并加入ModelMap
        //除了@ModelAttribute绑定参数之外，还可以通过@RequestParam从页面中传递参数
        users.put(user.getId(),user);
        return "success";
    }

    @RequestMapping(value="/{id}",method = RequestMethod.GET)
    public User getUser(@PathVariable Long id)
    {
        return users.get(id);
    }

    @RequestMapping(value="/{id}",method = RequestMethod.PUT)
    public String putUser(@PathVariable Long id,@ModelAttribute User user)
    {
        User u = users.get(id);
        u.setName(user.getName());
        u.setAge(user.getAge());
        users.put(id,u);
        return "success";
    }

    @RequestMapping(value="/{id}",method = RequestMethod.DELETE)
    public String deleteUser(@PathVariable Long id)
    {
        users.remove(id);
        return "success";
    }
}
